//
//  CentralViewController.m
//  BluetoothBattle
//
//  Created by LuckyStrike on 2017/5/22.
//  Copyright © 2017年 LuckyStrike. All rights reserved.
//


/**
  参考文章：http://www.cocoachina.com/ios/20170824/20369.html
 
 */

#import "CentralViewController.h"

@interface CentralViewController ()<CBCentralManagerDelegate,UITableViewDelegate,UITableViewDataSource,CBPeripheralDelegate>

/** tableView  */
@property (nonatomic,strong) IBOutlet UITableView *myTableView;
/** CBCentralManager  */
@property (nonatomic,strong) CBCentralManager *centralMgr;
/**   */
@property (nonatomic,strong) CBPeripheral *targetPeripheral;
/**   */
@property (nonatomic,strong) CBCharacteristic *targetCharacteristic;
/**   */
@property (nonatomic,strong) NSMutableArray *arrayBLE;

@property (strong, nonatomic) IBOutlet UILabel *recevicedInfoLab;

@property (strong, nonatomic) IBOutlet UITextView *putinView;

/**   */
@property (nonatomic,strong) CBPeripheral *selectPeripheral;

@end

@implementation CentralViewController

- (IBAction)searchPeripheral:(id)sender {
    
    self.centralMgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (IBAction)sendMessageBtn:(id)sender {
    
    NSData *data = [self.putinView.text dataUsingEncoding:NSUTF8StringEncoding];
    
    [self.targetPeripheral writeValue:data forCharacteristic:self.targetCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _arrayBLE = [NSMutableArray arrayWithCapacity:0];
    
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    
    
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"infoCell"];
 
}

- (BOOL)saveBLE:(BLEinfo*)info{
    for (BLEinfo *temp in self.arrayBLE) {
        if ([temp.discoveredPripheral.identifier.UUIDString isEqualToString:info.discoveredPripheral.identifier.UUIDString]) {
            return NO;
        }
    }
    [self.arrayBLE addObject:info];
    [self.myTableView reloadData];
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayBLE.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    BLEinfo *info = [self.arrayBLE objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@ %@",info.discoveredPripheral.name,info.rssi,info.discoveredPripheral.identifier.UUIDString];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BLEinfo *info = [self.arrayBLE objectAtIndex:indexPath.row];
    [self.centralMgr connectPeripheral:info.discoveredPripheral options:nil];
}

#pragma mark -- CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    
    NSLog(@"central  state%ld",(long)central.state);
    
    switch (central.state) {
            
        case CBManagerStatePoweredOn:
#if FILTERORNOT
            [self.centralMgr scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:SERVICE_UUID]]
                                                    options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
#else
            [self.centralMgr scanForPeripheralsWithServices:nil
                                                    options:nil];
#endif
            break;
        default:
            break;
    }
}
//搜索设备成功的回调
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI{
    
    BLEinfo *info = [[BLEinfo alloc] init];
    info.discoveredPripheral = peripheral;
    info.rssi = RSSI;
    
    [self saveBLE:info];
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
    NSLog(@"didFailToConnectPeripheral:%@",error);
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
    
    NSLog(@"丢失链接：%@",error);
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    self.targetPeripheral = peripheral;
    self.targetPeripheral.delegate = self;
    //过滤服务
#if FILTERORNOT
    [self.targetPeripheral discoverServices:@[[CBUUID UUIDWithString:SERVICE_UUID]]];
#else
    [self.targetPeripheral discoverServices:nil];
#endif
    
}

#pragma mark -- CBPeripheralDelegate

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error{
    NSLog(@"servive:%@",peripheral.services);

    for (CBService *service in peripheral.services) {
        if ([service.UUID.UUIDString isEqualToString:SERVICE_UUID]) {
            
            [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:CHARACTERISTIC_UUID_SEND]] forService:service];
            
        }
    }
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{
    
    NSLog(@"characteristics:%@",service.characteristics);
    
    for (CBCharacteristic *chara in service.characteristics) {
        
        if ([chara.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID_SEND]) {
            [peripheral setNotifyValue:YES forCharacteristic:chara];
            self.targetCharacteristic = chara;
        }
    }
}
//接受数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{


}





@end

@implementation BLEinfo


@end
